package com.planet.common.autoconfigure.sms;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.planet.common.autoconfigure.PlanetSenderAbstract;
import com.planet.common.autoconfigure.utils.CodeGenerateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;

/**
 * @Description: TODO 短信服务
 * @Author: mis_wu
 * @Date: 2023/8/25
 * @Company SMS
 **/
@Slf4j
public class PlanetSmsSender extends PlanetSenderAbstract {

    @Value("${ali.sms.accessKeyId}")
    private String accessKeyId;
    @Value("${ali.sms.secret}")
    private String secret;
    @Value("${ali.sms.singerName}")
    private String singerName; //短信签名
    @Value("${ali.sms.templateCode}")
    private String templateCode;//短息模板
    @Value("${ali.sms.regionId}")
    private String regionId;//短信服务区区域

    private PlanetSmsProperties planetSmsProperties;

    public void setPlanetSmsProperties(PlanetSmsProperties planetSmsProperties){
        this.planetSmsProperties = planetSmsProperties;
    }


    @Override
    public Boolean smsSend(String[] phones) {
        log.info("planet sms send，enable is:{}",planetSmsProperties.getEnable());
        if (phones == null || phones.length == 0){
            return false;
        }
        boolean result = false;
        for (String phone : phones) {
            result = this.sendCodeTemplate(phone);
            if(!result){
                log.error("planet user smsSend fail,phone is: {}",phone);
                //todo:重试机制
            }
        }

        return result;
    }

    private Boolean sendCodeTemplate(String phone){
        //连接
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);
        //构建请求
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        //自定义模板信息
        request.putQueryParameter("PhoneNumbers", phone);
        //你的阿里云签名的名称
        request.putQueryParameter("SignName", singerName);
        request.putQueryParameter("TemplateCode", templateCode);
        //request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
        //构建验证码
        HashMap<String, Object> map = new HashMap<>();
        String code = CodeGenerateUtil.get6BitCode();
        map.put("code", code);
        request.putQueryParameter("TemplateParam", JSON.toJSONString(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("阿里云短信响应信息 {}",response.getData());
            return true;
        } catch (ServerException e) {
            log.error("planet send sms error[ServerException],reason: {}",e.getMessage(),e);
            throw new RuntimeException("提示:阿里云服务异常!");
        } catch (ClientException e) {
            log.error("planet send sms error[ClientException],reason: {}",e.getMessage(),e);
            throw new RuntimeException("提示:短信发送失败!");
        }
    }
}
